<template>
  <DistributorLayout>
    <div class="payment-links-page">
      <!-- 页面标题区域 -->
      <div class="page-header">
        <div class="header-left">
          <h1 class="page-title">代付链接管理</h1>
          <p class="page-subtitle">管理您创建的所有代付链接，查看使用情况和佣金收益</p>
        </div>
        <div class="header-right">
          <button class="btn-create-link" @click="handleCreateLink">
            <i class="fas fa-plus"></i> 创建新链接
          </button>
        </div>
      </div>

      <!-- 筛选区域 -->
      <div class="filter-section">
        <div class="search-box">
          <i class="fas fa-search search-icon"></i>
          <input
            type="text"
            class="search-input"
            placeholder="搜索商品名称或链接ID"
            v-model="searchQuery"
            @input="handleSearch"
          />
          <button class="clear-search" v-if="searchQuery" @click="clearSearch">
            <i class="fas fa-times"></i>
          </button>
        </div>
        
        <div class="filter-row">
          <div class="date-picker">
            <div class="date-label">创建日期</div>
            <div class="date-inputs">
              <input
                type="date"
                class="date-input"
                v-model="dateRange.start"
                @change="handleFilterChange"
              />
              <span class="date-separator">至</span>
              <input
                type="date"
                class="date-input"
                v-model="dateRange.end"
                @change="handleFilterChange"
              />
            </div>
          </div>
          
          <div class="status-filter">
            <div class="status-label">链接状态</div>
            <select class="status-select" v-model="statusFilter" @change="handleFilterChange">
              <option value="all">全部状态</option>
              <option value="active">启用中</option>
              <option value="inactive">已停用</option>
              <option value="expired">已过期</option>
            </select>
          </div>
          
          <button class="btn-reset-filters" @click="resetFilters">
            <i class="fas fa-redo"></i> 重置筛选
          </button>
        </div>
        
        <!-- 筛选标签 -->
        <div class="filter-tags" v-if="hasActiveFilters">
          <div class="tags-label">已筛选:</div>
          <div class="tags-list">
            <div class="filter-tag" v-if="searchQuery">
              <span>关键词: {{ searchQuery }}</span>
              <button class="tag-remove" @click="clearSearch">
                <i class="fas fa-times"></i>
              </button>
            </div>
            <div class="filter-tag" v-if="dateRange.start || dateRange.end">
              <span>日期: {{ formatDateRange(dateRange) }}</span>
              <button class="tag-remove" @click="clearDateRange">
                <i class="fas fa-times"></i>
              </button>
            </div>
            <div class="filter-tag" v-if="statusFilter !== 'all'">
              <span>状态: {{ getStatusLabel(statusFilter) }}</span>
              <button class="tag-remove" @click="clearStatusFilter">
                <i class="fas fa-times"></i>
              </button>
            </div>
          </div>
          <button class="clear-all-tags" @click="resetFilters">
            清除全部
          </button>
        </div>
      </div>

      <!-- 链接表格 -->
      <PaymentLinksTable
        :links="filteredLinks"
        :loading="loading"
        :itemsPerPage="10"
        @sort="handleSort"
        @copy="handleCopyLink"
        @share="handleShareLink"
        @view="handleViewLink"
        @delete="handleDeleteLink"
        @batch-delete="handleBatchDelete"
        @batch-export="handleBatchExport"
        @toggle-status="handleToggleStatus"
        @update-remark="updateLinkRemark"
      />

      <!-- 页面为空时的提示 -->
      <div class="empty-state" v-if="!loading && !links.length">
        <div class="empty-icon">
          <i class="fas fa-link"></i>
        </div>
        <h3 class="empty-title">暂无代付链接</h3>
        <p class="empty-description">
          您还没有创建任何代付链接，点击下方按钮创建第一个链接
        </p>
        <button class="btn-create-first-link" @click="handleCreateLink">
          <i class="fas fa-plus"></i> 创建新链接
        </button>
      </div>

      <!-- 操作成功提示 -->
      <transition name="fade">
        <div class="operation-message" v-if="operationMessage.show">
          <div class="message-content" :class="operationMessage.type">
            <i class="fas" :class="getMessageIcon()"></i>
            <span>{{ operationMessage.text }}</span>
          </div>
        </div>
      </transition>
      
      <!-- 链接详情抽屉 -->
      <LinkDetailDrawer
        v-model:visible="detailDrawerVisible"
        :linkId="currentLinkId"
        @copy="handleCopyLinkInDrawer"
        @share="handleShareLinkInDrawer"
        @toggle-status="handleToggleStatusInDrawer"
        @delete="handleDeleteLinkInDrawer"
      />
    </div>
  </DistributorLayout>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import DistributorLayout from './DistributorLayout.vue'
import PaymentLinksTable from '@/components/distributor/links/PaymentLinksTable.vue'
import LinkDetailDrawer from '@/components/distributor/links/LinkDetailDrawer.vue'
import { generatePaymentLinksData } from '@/utils/mockData'

// 链接数据
const links = ref<any[]>([])
const loading = ref(true)

// 筛选状态
const searchQuery = ref('')
const dateRange = ref({
  start: '',
  end: ''
})
const statusFilter = ref('all')

// 排序状态
const sortConfig = ref({
  column: '',
  direction: 'desc' as 'asc' | 'desc'
})

// 操作提示信息
const operationMessage = ref({
  show: false,
  text: '',
  type: 'success' // success, error, warning, info
})

// 链接详情抽屉状态
const detailDrawerVisible = ref(false)
const currentLinkId = ref('')

// 获取链接数据
const fetchLinks = async () => {
  loading.value = true
  try {
    // 模拟API请求延迟
    await new Promise(resolve => setTimeout(resolve, 800))
    // 使用mock数据
    links.value = generatePaymentLinksData(25)
  } catch (error) {
    console.error('获取链接数据失败:', error)
    showMessage('获取数据失败，请重试', 'error')
  } finally {
    loading.value = false
  }
}

// 计算是否有激活的筛选条件
const hasActiveFilters = computed(() => {
  return searchQuery.value || dateRange.value.start || dateRange.value.end || statusFilter.value !== 'all'
})

// 过滤链接
const filteredLinks = computed(() => {
  let result = [...links.value]
  
  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    result = result.filter(link => 
      link.productName.toLowerCase().includes(query) || 
      link.id.toLowerCase().includes(query)
    )
  }
  
  // 日期过滤
  if (dateRange.value.start) {
    const startDate = new Date(dateRange.value.start)
    result = result.filter(link => {
      const createdDate = new Date(link.createdAt)
      return createdDate >= startDate
    })
  }
  
  if (dateRange.value.end) {
    const endDate = new Date(dateRange.value.end)
    endDate.setHours(23, 59, 59, 999) // 设置为当天结束时间
    result = result.filter(link => {
      const createdDate = new Date(link.createdAt)
      return createdDate <= endDate
    })
  }
  
  // 状态过滤
  if (statusFilter.value !== 'all') {
    if (statusFilter.value === 'expired') {
      result = result.filter(link => {
        const expiryDate = new Date(link.expiresAt)
        return expiryDate < new Date()
      })
    } else {
      result = result.filter(link => 
        (statusFilter.value === 'active' && link.isActive) || 
        (statusFilter.value === 'inactive' && !link.isActive)
      )
    }
  }
  
  // 应用排序
  if (sortConfig.value.column) {
    result.sort((a, b) => {
      let aValue, bValue
      
      switch (sortConfig.value.column) {
        case 'price':
          aValue = a.discountPrice
          bValue = b.discountPrice
          break
        case 'createdAt':
          aValue = new Date(a.createdAt).getTime()
          bValue = new Date(b.createdAt).getTime()
          break
        case 'usageCount':
          aValue = a.usageCount
          bValue = b.usageCount
          break
        default:
          return 0
      }
      
      if (sortConfig.value.direction === 'asc') {
        return aValue > bValue ? 1 : -1
      } else {
        return aValue < bValue ? 1 : -1
      }
    })
  }
  
  return result
})

// 处理搜索
const handleSearch = () => {
  // 这里可以添加防抖处理
}

// 处理筛选变化
const handleFilterChange = () => {
  // 筛选条件变化时的处理
}

// 重置所有筛选条件
const resetFilters = () => {
  searchQuery.value = ''
  dateRange.value = { start: '', end: '' }
  statusFilter.value = 'all'
}

// 清除搜索
const clearSearch = () => {
  searchQuery.value = ''
}

// 清除日期范围
const clearDateRange = () => {
  dateRange.value = { start: '', end: '' }
}

// 清除状态筛选
const clearStatusFilter = () => {
  statusFilter.value = 'all'
}

// 格式化日期范围显示
const formatDateRange = (range: { start: string, end: string }) => {
  if (range.start && range.end) {
    return `${formatShortDate(range.start)} 至 ${formatShortDate(range.end)}`
  } else if (range.start) {
    return `${formatShortDate(range.start)} 起`
  } else if (range.end) {
    return `至 ${formatShortDate(range.end)}`
  }
  return ''
}

// 简化日期格式
const formatShortDate = (dateString: string) => {
  const date = new Date(dateString)
  return `${date.getMonth() + 1}月${date.getDate()}日`
}

// 获取状态标签
const getStatusLabel = (status: string) => {
  switch (status) {
    case 'active': return '启用中'
    case 'inactive': return '已停用'
    case 'expired': return '已过期'
    default: return '全部状态'
  }
}

// 获取消息图标
const getMessageIcon = () => {
  switch (operationMessage.value.type) {
    case 'success': return 'fa-check-circle'
    case 'error': return 'fa-times-circle'
    case 'warning': return 'fa-exclamation-triangle'
    case 'info': return 'fa-info-circle'
    default: return 'fa-info-circle'
  }
}

// 显示操作提示消息
const showMessage = (text: string, type: 'success' | 'error' | 'warning' | 'info' = 'success') => {
  operationMessage.value = {
    show: true,
    text,
    type
  }
  
  // 自动隐藏消息
  setTimeout(() => {
    operationMessage.value.show = false
  }, 3000)
}

// 处理创建新链接
const handleCreateLink = () => {
  // 跳转到商品列表页以创建新链接
  showMessage('功能开发中，请稍后再试', 'info')
}

// 处理表格排序
const handleSort = (column: string, direction: 'asc' | 'desc') => {
  sortConfig.value = { column, direction }
}

// 处理复制链接
const handleCopyLink = (link: any) => {
  try {
    navigator.clipboard.writeText(link.url)
    showMessage('链接已复制到剪贴板')
  } catch (err) {
    console.error('复制失败:', err)
    showMessage('复制链接失败，请手动复制', 'error')
  }
}

// 处理分享链接
const handleShareLink = (link: any) => {
  showMessage('分享功能开发中', 'info')
}

// 处理查看链接详情
const handleViewLink = (link: any) => {
  currentLinkId.value = link.id
  detailDrawerVisible.value = true
}

// 处理删除链接
const handleDeleteLink = (link: any) => {
  if (confirm(`确定要删除链接"${link.name}"吗？`)) {
    links.value = links.value.filter(item => item.id !== link.id)
    showMessage('链接已删除')
  }
}

// 处理批量删除
const handleBatchDelete = (ids: string[]) => {
  if (confirm(`确定要删除选中的 ${ids.length} 个链接吗？`)) {
    links.value = links.value.filter(link => !ids.includes(link.id))
    showMessage(`已删除 ${ids.length} 个链接`)
  }
}

// 处理批量导出
const handleBatchExport = (ids: string[]) => {
  showMessage(`已导出 ${ids.length} 个链接数据`, 'success')
}

// 处理切换链接状态
const handleToggleStatus = (link: any, status: boolean) => {
  // 在实际项目中会调用API修改状态
  const linkIndex = links.value.findIndex(item => item.id === link.id)
  if (linkIndex >= 0) {
    links.value[linkIndex].isActive = status
    links.value[linkIndex].status = status ? 'active' : 'inactive'
    showMessage(`链接状态已${status ? '启用' : '停用'}`)
  }
}

// 处理抽屉中的复制链接
const handleCopyLinkInDrawer = (url: string) => {
  try {
    navigator.clipboard.writeText(url)
    showMessage('链接已复制到剪贴板')
  } catch (err) {
    console.error('复制失败:', err)
    showMessage('复制链接失败，请手动复制', 'error')
  }
}

// 处理抽屉中的分享链接
const handleShareLinkInDrawer = (linkDetail: any) => {
  showMessage('分享功能开发中', 'info')
}

// 处理抽屉中的切换链接状态
const handleToggleStatusInDrawer = (linkId: string, status: boolean) => {
  const linkIndex = links.value.findIndex(item => item.id === linkId)
  if (linkIndex >= 0) {
    links.value[linkIndex].isActive = status
    links.value[linkIndex].status = status ? 'active' : 'inactive'
    showMessage(`链接状态已${status ? '启用' : '停用'}`)
  }
}

// 处理抽屉中的删除链接
const handleDeleteLinkInDrawer = (linkId: string) => {
  links.value = links.value.filter(item => item.id !== linkId)
  showMessage('链接已删除')
  detailDrawerVisible.value = false
}

// 添加保存备注的方法
const updateLinkRemark = async (linkId: string, remark: string) => {
  try {
    // 更新本地数据
    const linkIndex = links.value.findIndex(link => link.id === linkId)
    if (linkIndex !== -1) {
      links.value[linkIndex].remark = remark
    }
    
    // 在实际项目中这里会发送API请求保存备注
    // 示例: await api.updateLinkRemark(linkId, remark)
    await new Promise(resolve => setTimeout(resolve, 300)) // 模拟网络请求
    
    // 显示成功提示
    showMessage('备注已保存')
  } catch (error) {
    console.error('保存备注失败', error)
    showMessage('备注保存失败，请重试', 'error')
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchLinks()
})
</script>

<style scoped lang="scss">
.payment-links-page {
  background: white;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  
  h1 {
    margin-top: 0;
    margin-bottom: 16px;
    color: #2F3542;
  }
  
  p {
    color: #6C757D;
    line-height: 1.6;
  }

  // 页面标题区域
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    
    .header-left {
      .page-title {
        font-size: 24px;
        font-weight: 700;
        color: #2F3542;
        margin: 0 0 6px 0;
      }
      
      .page-subtitle {
        font-size: 14px;
        color: #6C757D;
        margin: 0;
      }
    }
    
    .header-right {
      .btn-create-link {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        padding: 8px 16px;
        background-color: #FF4757;
        color: #fff;
        border: none;
        border-radius: 6px;
        font-size: 14px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.2s ease;
        
        i {
          margin-right: 6px;
        }
        
        &:hover {
          background-color: darken(#FF4757, 10%);
          transform: translateY(-2px);
          box-shadow: 0 3px 8px rgba(255, 71, 87, 0.3);
        }
      }
    }
  }
  
  // 筛选区域
  .filter-section {
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    padding: 20px;
    margin-bottom: 24px;
    
    .search-box {
      position: relative;
      margin-bottom: 16px;
      
      .search-icon {
        position: absolute;
        left: 12px;
        top: 50%;
        transform: translateY(-50%);
        color: #ADB5BD;
      }
      
      .search-input {
        width: 100%;
        height: 42px;
        padding-left: 36px;
        padding-right: 36px;
        border: 1px solid #DFE3E8;
        border-radius: 6px;
        font-size: 14px;
        color: #2F3542;
        
        &:focus {
          outline: none;
          border-color: #FF4757;
          box-shadow: 0 0 0 2px rgba(255, 71, 87, 0.2);
        }
        
        &::placeholder {
          color: #ADB5BD;
        }
      }
      
      .clear-search {
        position: absolute;
        right: 12px;
        top: 50%;
        transform: translateY(-50%);
        background: none;
        border: none;
        color: #ADB5BD;
        cursor: pointer;
        padding: 4px;
        
        &:hover {
          color: #6C757D;
        }
      }
    }
    
    .filter-row {
      display: flex;
      flex-wrap: wrap;
      gap: 16px;
      margin-bottom: 16px;
      
      .date-picker {
        flex: 1;
        min-width: 300px;
        
        .date-label {
          font-size: 13px;
          color: #6C757D;
          margin-bottom: 6px;
        }
        
        .date-inputs {
          display: flex;
          align-items: center;
          
          .date-input {
            flex: 1;
            height: 36px;
            padding: 0 12px;
            border: 1px solid #DFE3E8;
            border-radius: 4px;
            font-size: 14px;
            color: #2F3542;
          }
          
          .date-separator {
            margin: 0 8px;
            color: #ADB5BD;
          }
        }
      }
      
      .status-filter {
        width: 200px;
        
        .status-label {
          font-size: 13px;
          color: #6C757D;
          margin-bottom: 6px;
        }
        
        .status-select {
          width: 100%;
          height: 36px;
          padding: 0 12px;
          border: 1px solid #DFE3E8;
          border-radius: 4px;
          font-size: 14px;
          color: #2F3542;
          background-color: #fff;
          
          &:focus {
            outline: none;
            border-color: #FF4757;
            box-shadow: 0 0 0 2px rgba(255, 71, 87, 0.2);
          }
        }
      }
      
      .btn-reset-filters {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        height: 36px;
        padding: 0 16px;
        margin-top: 19px; // 对齐其他元素的输入框
        background-color: #F0F2F5;
        border: none;
        border-radius: 4px;
        font-size: 13px;
        color: #2F3542;
        cursor: pointer;
        transition: all 0.2s;
        
        i {
          margin-right: 6px;
        }
        
        &:hover {
          background-color: #DFE3E8;
        }
      }
    }
    
    // 筛选标签区域
    .filter-tags {
      display: flex;
      align-items: center;
      
      .tags-label {
        font-size: 13px;
        color: #6C757D;
        margin-right: 8px;
      }
      
      .tags-list {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        flex: 1;
        
        .filter-tag {
          display: inline-flex;
          align-items: center;
          padding: 4px 10px;
          background-color: #F3F4F6;
          border-radius: 4px;
          font-size: 12px;
          color: #4B5563;
          
          .tag-remove {
            background: none;
            border: none;
            color: #9CA3AF;
            cursor: pointer;
            margin-left: 6px;
            padding: 0;
            font-size: 10px;
            
            &:hover {
              color: #6B7280;
            }
          }
        }
      }
      
      .clear-all-tags {
        background: none;
        border: none;
        padding: 4px 8px;
        font-size: 12px;
        color: #FF4757;
        cursor: pointer;
        
        &:hover {
          text-decoration: underline;
        }
      }
    }
  }
  
  // 空状态
  .empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 80px 20px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    
    .empty-icon {
      font-size: 64px;
      color: #DFE3E8;
      margin-bottom: 24px;
    }
    
    .empty-title {
      font-size: 20px;
      font-weight: 600;
      color: #2F3542;
      margin: 0 0 12px 0;
    }
    
    .empty-description {
      font-size: 14px;
      color: #6C757D;
      margin: 0 0 24px 0;
      text-align: center;
      max-width: 400px;
    }
    
    .btn-create-first-link {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      padding: 10px 20px;
      background-color: #FF4757;
      color: #fff;
      border: none;
      border-radius: 6px;
      font-size: 14px;
      font-weight: 600;
      cursor: pointer;
      transition: all 0.2s ease;
      
      i {
        margin-right: 8px;
      }
      
      &:hover {
        background-color: darken(#FF4757, 10%);
        transform: translateY(-2px);
        box-shadow: 0 3px 8px rgba(255, 71, 87, 0.3);
      }
    }
  }
  
  // 操作提示信息
  .operation-message {
    position: fixed;
    top: 20px;
    right: 20px;
    z-index: 1000;
    
    .message-content {
      display: flex;
      align-items: center;
      padding: 12px 16px;
      border-radius: 4px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
      color: #fff;
      font-size: 14px;
      
      i {
        margin-right: 8px;
      }
      
      &.success {
        background-color: #28A745;
      }
      
      &.error {
        background-color: #DC3545;
      }
      
      &.warning {
        background-color: #FFC107;
        color: #212529;
      }
      
      &.info {
        background-color: #17A2B8;
      }
    }
  }
  
  // 淡入淡出动画
  .fade-enter-active,
  .fade-leave-active {
    transition: opacity 0.3s, transform 0.3s;
  }
  
  .fade-enter-from,
  .fade-leave-to {
    opacity: 0;
    transform: translateY(-20px);
  }
}

// 响应式样式
@media (max-width: 768px) {
  .payment-links-page {
    .page-header {
      flex-direction: column;
      align-items: flex-start;
      
      .header-left {
        margin-bottom: 16px;
      }
    }
    
    .filter-section {
      .filter-row {
        flex-direction: column;
        gap: 12px;
        
        .date-picker,
        .status-filter {
          width: 100%;
        }
        
        .btn-reset-filters {
          margin-top: 0;
          width: 100%;
        }
      }
    }
  }
}
</style> 